<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesVisible = true">
            添加角色
          </el-button>
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom',index1==0 ? 'bdtop': '','vcenter']"
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
               <el-tag closable @close="removePower(scope.row,item1.id)"> {{ item1.authName }}</el-tag>
               <i class="el-icon-caret-right"></i>

              </el-col>
              <!-- 渲染二级 -->
              <el-col :span="19" >
                <el-row :class="[index2==0?'':'bdtop','vcenter']" v-for="(item2,index2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                     <el-tag type="success" closable @close="removePower(scope.row,item2.id)" >
                        {{item2.authName}}
                     </el-tag>
                      <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染3级权限 -->
                  <el-col :span="18">
                    <el-tag v-for="( item3 ) in item2.children " :key='item3.id ' type="warning" closable @close="removePower(scope.row,item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>

          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="changeRolesFun(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteChangeRoles(scope.row.id)"
              >删除</el-button
            >
            <el-button size="mini" type="warning" icon="el-icon-search"
             @click="showSetpower(scope.row)" >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->

    <el-dialog
      title="添加角色"
      :visible.sync="addRolesVisible"
      @close="rolesClose"
      width="50%"
    >
      <!-- 内容主体 -->
      <el-form
        :model="addRoles"
        :rules="addRolesRules"
        ref="addRolesRef"
        label-width="80px"
      >
        <el-form-item label="角色" prop="roleName">
          <el-input v-model="addRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolesFun">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="changeRolesVisible"
      @close="changerolesClose"
      width="50%"
    >
      <el-form
        :model="changeRoles"
        :rules="changeRolesRules"
        ref="changeRolesRef"
        label-width="80px"
      >
        <el-form-item label="角色" prop="roleName">
          <el-input v-model="changeRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="changeRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeRolesInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="powerDialig"
      @close="powerClose"
      width="350">
      <!-- 树型控件 -->
      <el-tree :data="rightsList" :props="treeProps"
       show-checkbox node-key="id" ref="treeRef"
       default-expand-all :default-checked-keys="defKeys">

      </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="powerDialig = false">取 消</el-button>
        <el-button type="primary" @click="allotRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created () {
    this.getRolesList()
  },
  data () {
    return {
      // 角色列表
      rolesList: [],
      addRolesDialog: false,
      addRolesVisible: false,
      changeRolesDialog: false,
      changeRolesVisible: false,

      addRoles: {
        roleName: 'blank',
        roleDesc: '主管'
      },
      addRolesRules: {
        roleName: [
          { required: true, message: '请输入角色', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 16 个字符', trigger: 'blur' }
        ]
      },
      changeRolesRules: {
        roleName: [
          { required: true, message: '请输入角色', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 16 个字符', trigger: 'blur' }
        ]
      },
      changeRoles: {},
      changeRolesRef: {},
      // 权限对话框的分配显示隐藏

      powerDialig: false,
      rightsList: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      defKeys: [],
      // 当前即将分配权限的id
      roleId: ''

    }
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) { return this.$message.error('获取角色列表失败') }
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    // 添加角色
    addRolesFun () {
      this.$refs.addRolesRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRoles)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.addRolesVisible = false
        this.getRolesList()
      })
    },
    rolesClose () {
      this.$refs.addRolesRef.resetFields()
    },
    async changeRolesFun (e) {
      const { data: res } = await this.$http.get('roles/' + e)
      if (res.meta.status !== 200) return this.$message.error('查询角色失败')
      this.changeRoles = res.data
      // console.log(this.changeRoles)
      this.changeRolesVisible = true
    },
    changerolesClose () {
      this.$refs.changeRolesRef.resetFields()
    },
    changeRolesInfo () {
      this.$refs.changeRolesRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.put(
          'roles/' + this.changeRoles.roleId,
          {
            roleName: this.changeRoles.roleName,
            roleDesc: this.changeRoles.roleDesc
          }
        )
        // console.log(res.meta.status)
        if (res.meta.status !== 200) {
          return this.$message.error('更新角色失败')
        }
        // 关闭对话框
        this.changeRolesVisible = false
        // 更新数据
        this.getRolesList()
        this.$message.success('更新角色信息成功')
      })
    },
    // 删除角色
    async deleteChangeRoles (e) {
      const res = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (res !== 'confirm') return this.$message.info('已取消')
      const { data: o } = await this.$http.delete('roles/' + e)
      // console.log(o.meta.status)
      if (o.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')

      this.getRolesList()
    },
    // 删除权限
    async removePower (role, pw) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${pw}`)
      if (res.meta.status !== 200) return this.$message.error('删除权限失败')
      this.$message.success('删除权限成功')
      // this.getRolesList()
      role.children = res.data
    },
    async showSetpower (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取信息失败')
      // 权限数据保存到data
      this.rightsList = res.data
      // console.log(this.rolesList)
      // 递归三级节点
      this.getLeafKeys(role, this.defKeys)
      this.powerDialig = true
    },
    // 如果当前node的节点不包含children属性，则是三级属性
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      // 递归获取
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    powerClose () {
      this.defKeys = []
    },
    async  allotRoles () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.powerDialig = false
      // console.log(idStr)
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
